package com.example.deliveryapplication

import android.app.DownloadManager
import android.content.Context
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import androidx.core.content.FileProvider
import kotlinx.android.synthetic.main.activity_new_plan.mConfirmBTN
import kotlinx.android.synthetic.main.activity_re_back.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.BufferedInputStream
import java.io.File
import java.io.FileOutputStream
import java.net.URL
import kotlin.system.exitProcess

class ReBackActivity : AppCompatActivity() {
    private val scope = CoroutineScope(Dispatchers.Main)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_re_back)
        mConfirmBTN.setOnClickListener {
            val link=linkTV.text.toString()
            if(link.isNotEmpty()&&link.contains("https://")){
                //downloadFile(this,link,"database")
               commonDialog("确认恢复数据么，此举可能覆盖当前的数据"){
                   scope.launch {
                       try {
                           downloadDatabaseFileToInternalStorage(applicationContext,link,"app_database")
                       }catch (e:Exception){
                           showToast("下载失败")
                       }
                   }
               }

            }else{
                showToast("请先输入管理员提供的正确的链接")
            }
        }
    }
    fun downloadFile(context: Context, fileUrl: String, fileName: String) {
        val request = DownloadManager.Request(Uri.parse(fileUrl))
            .setTitle(fileName)
            .setDescription("Downloading")
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setDestinationInExternalFilesDir(context, null, fileName) // 将文件保存到应用的内部存储目录下

        val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        downloadManager.enqueue(request)
    }
    suspend fun downloadDatabaseFileToInternalStorage(context: Context, fileUrl: String, fileName: String) {
        withContext(Dispatchers.IO) {
            val url = URL(fileUrl)
            val connection = url.openConnection()
            connection.connect()

            val input = BufferedInputStream(url.openStream())
            val dbFile = context.getDatabasePath(fileName)
            val shm=context.getDatabasePath("${fileName}-shm")
            val wal=context.getDatabasePath("${fileName}-wal")
            if(dbFile.exists()){
                dbFile.delete()
            }
            if(shm.exists()){
                shm.delete()
            }
            if(wal.exists()){
                wal.delete()
            }
            val output = FileOutputStream(dbFile)

            val data = ByteArray(1024)
            var total: Long = 0
            var count: Int
            while (input.read(data).also { count = it } != -1) {
                total += count.toLong()
                output.write(data, 0, count)
            }

            output.flush()
            output.close()
            input.close()
            //恢复成功


        }
        withContext(Dispatchers.Main) {
            showToast("恢复成功，请重新启动app")
            exitProcess(0)
        }

    }
}